<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import { ref, provide, onMounted, onBeforeMount, onUnmounted } from "vue";
import $ from 'jquery'

import { invoke } from "@tauri-apps/api/tauri";
import { emit, listen } from "@tauri-apps/api/event";
import { event } from "@tauri-apps/api";

import * as echarts from 'echarts';
import 'echarts-liquidfill'

var cpuChart = null;
var meomoryChart = null;
var swapChart = null;

var chartInstance = null;



const start_listener = async () => {
  return await listen("collet_cpu", event => {
    //console.log(`event id ${event.id}`)
    const { cpu_usage, used_memory, free_memory, used_swap, free_swap } = event.payload;

    let total_memory = (used_memory + free_memory).toFixed(1);
    let total_swap = (used_swap + free_swap).toFixed(1);

    let color = '#EEEEEE';
    if (cpu_usage > 80) {
      color =  '#fd666d';
    } else if (cpu_usage > 60) {
      color = '#ffc53d';
    } else if (cpu_usage > 50) {
      color = 'rgb(128, 224, 145)';
    }else {
      color = 'rgb(39, 192, 26)';
    }

    var chartOption = {
      series: [{ // 水球图
        type: 'liquidFill', // 水球图
        name: 'Liquid Fill1', // 水球图名称
        radius: '100%', // 水球图半径
        itemStyle: { // 水球图样式
          opacity: 1, // 水球图透明度
          shadowBlur: 0, // 波浪的阴影范围
          textStyle: {
            color: '#000', // 水球图内的文字颜色
            fontSize: 20
        },
        },
        data: [{ // 水球图数据
          name: 'CPU', // 水球图数据名称
          direction: 'right',// 水球图数据方向
          value: parseFloat((cpu_usage / 100).toFixed(2)), // 水球图数据值  
          itemStyle: { // 水球图数据样式
            opacity: 1, // 水球图数据透明度
            color: color, // 水球图数据正常样式颜色
          },
        }],
        backgroundStyle: {   // 设置水球图内部背景色
          // borderColor: '#4348EC',
          // borderWidth: 10
          color: "#EEEEEE",//水球图内部背景色
        },
        label: {   // 设置百分比展示
          color: "inherit", // 百分比颜色
          textStyle: { // 百分比正常样式字体
            fontSize: 20, // 百分比正常样式字体大小
            color: '#333'
          },
          formatter: function (param) { // 百分比正常样式字体格式
            return param.value * 100 + '%'; // 百分比正常样式字体格式
          }
        },
        //外部细圆
        outline: { // 是否显示外圈
          show: true,
          borderDistance: 6, // 外部圆线距离水球的距离
          itemStyle: { // 外部圆线样式
            borderWidth: 3, // 外部圆线宽度
            borderColor: color, // 外部圆线颜色
            //shadowBlur: 20, // 外部圆线阴影范围
            //shadowColor: 'rgba(0, 0, 0, 0.25)' // 外部圆线阴影颜色
          }
        },
      }],
    };

    chartInstance.setOption(chartOption);

    var cpuOption = {
      series: [
        {
          title: {
            offsetCenter: [0, '80%'],
            fontSize: 16,
            color: 'inherit',
          },
          type: 'gauge',
          radius: '80%',
          axisLine: {
            lineStyle: {
              width: 20,
              //roundCap: true,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
              shadowBlur: 5,
              color: [
                [0.2, 'rgb(39, 192, 26)'],
                [0.5, 'rgb(128, 224, 145)'],
                [0.8, '#fae208'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            show: true,
            overlap: true,
            roundCap: true,
            offsetCenter: [0, 0],
            itemStyle: {
              color: 'inherit'
            }
          },
          axisTick: {
            distance: -20,
            length: 6,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          splitLine: {
            distance: -20,
            length: 20,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          axisLabel: {
            color: 'inherit',
            distance: 25,
            fontSize: 10
          },
          detail: {
            valueAnimation: true,
            formatter: '{value}%',
            color: 'inherit',
            fontSize: 12,
            offsetCenter: [0, '50%'],
          },
          data: [
            {
              value: cpu_usage.toFixed(1),
              name: 'CPU',
            }
          ],
          label: {
            color: 'inherit',
          }
        }
      ]
    };

    cpuChart && cpuChart.setOption(cpuOption);

    var memoryOption = {
      title: {
        text: "Memory",
        left: "center",
        top: "160",
        textStyle: {
          color: '#7a7a7a',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c}GB({d}%)"
      },
      legend: {
        show: false,
      },
      series: [
        {
          name: "Memory",
          type: "pie",
          radius: ["40%", "70%"],
          center: ["50%", "50%"],
          top: "auto",
          startAngle: 240,
          endAngle: 300,
          data: [
            {
              value: parseInt(used_memory.toFixed(1)),
              name: "usage",
              selected: false,
              label: {
                show: true,
                position: "center",
                fontSize: 12,
                formatter: `{c}/${total_memory}GB\n{d}%`
              },
            },
            {
              value: parseInt(free_memory.toFixed(1)),
              name: "free",
              selected: false,
              select: {
                'disabled': true
              },
              label: {
                show: false,
              },
            },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            },
          },
          select: {
            disabled: true
          },
          label: {
            color: 'inherit'
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            color: function (params) {
              if (params.name === "usage") {
                if (params.value > 80) {
                  return 'red';
                } else {
                  return 'rgb(128, 224, 145)';
                }
              }
              return '#EEEEEE'
            }
          },
          animation: false
        }
      ]
    };

    meomoryChart && meomoryChart.setOption(memoryOption);

    var swapOption = {
      title: {
        text: "Swap",
        left: "center",
        top: "160",
        textStyle: {
          color: '#7a7a7a',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} GB ({d}%)"
      },
      legend: {
        show: false,
      },
      series: [
        {
          name: "Swap",
          type: "pie",
          radius: ["40%", "70%"],
          center: ["50%", "50%"],
          top: 5,
          startAngle: 240,
          endAngle: 300,
          data: [
            {
              value: parseInt(used_swap.toFixed(1)),
              name: "usage",
              selected: true,
              label: {
                show: true,
                position: "center",
                fontSize: 12,
                formatter: `{c}/${parseInt(total_swap)} GB\n{d}%`
              },
            },
            {
              value: parseInt(free_swap.toFixed(1)),
              name: "free",
              selected: false,
              select: {
                'disabled': true
              },
              label: {
                show: false,
              },
            },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            },
          },
          label: {
            color: "inherit"
          },
          labelLine: {
            show: false
          },
          itemStyle: {
            color: function (params) {
              if (params.name === "usage") {
                if (params.value > 80) {
                  return 'red';
                } else {
                  return 'rgb(128, 224, 145)';
                }
              }
              return '#EEEEEE'
            }
          },
          animation: false
        }
      ]
    };

    swapChart && swapChart.setOption(swapOption);
  })
};

var unlisten = null


onBeforeMount(() => {

})

onBeforeMount(() => {
  invoke("collet_cpu");
  unlisten = start_listener();
})


onMounted(() => {
  let _width = $("#custom-container").width();
  let _height = $("#custom-container").height();
  console.log(_width, _height);

  var chartDom = document.getElementById('cpu-chart');
  // { width: _width, height: _height }
  cpuChart = echarts.init(chartDom);
  // window.onresize = function () {
  //   myChart.resize();
  // };

  meomoryChart = echarts.init(document.getElementById('memory-chart'));

  swapChart = echarts.init(document.getElementById('swap-chart'));

  //获取对应的dom元素
  const el = document.querySelector('.chart-box1')
  // 初始化
  chartInstance = echarts.init(el)



  window.addEventListener('resize', function () {
    let _width = $("#custom-container").width();
    let _height = $("#custom-container").height();
    console.log("resize", _width, _height);

    cpuChart && cpuChart.resize();

    meomoryChart && meomoryChart.resize();

    swapChart && swapChart.resize();

    chartInstance && chartInstance.resize();
  });
}
)

onUnmounted(async () => {
  if (unlisten != null) {
    await emit('StopEvent', { is_stop: true });
    unlisten.then((ok) => {
      ok();
      unlisten = null;
      console.log("stop success");
    }).catch((err) => {
      console.log("stop fail", err);
    });
  }
})

</script>

<template>
  <!-- <div id="custom-container" data-tauri-drag-region oncontextmenu="return false;" ondragstart="return false;"
    onselectstart="return false;" onselect="document.selection.empty();">
  </div> -->
  <div id="custom-container" data-tauri-drag-region>
    <el-carousel height="280px" direction="vertical" :autoplay="true" indicator-position="none" data-tauri-drag-region>

      <el-carousel-item data-tauri-drag-region>
        <div class="ball01" data-tauri-drag-region>
          <div class="chart-box1" data-tauri-drag-region></div>
        </div>
      </el-carousel-item>

      <el-carousel-item data-tauri-drag-region>
        <div class="ball01" data-tauri-drag-region>
          <div id="cpu-chart" data-tauri-drag-region></div>
        </div>
      </el-carousel-item>

      <el-carousel-item data-tauri-drag-region>
        <div class="ball01" data-tauri-drag-region>
          <div id="memory-chart" data-tauri-drag-region></div>
        </div>
      </el-carousel-item>

      <el-carousel-item data-tauri-drag-region>
        <div class="ball01" data-tauri-drag-region>
          <div id="swap-chart" data-tauri-drag-region></div>
        </div>
      </el-carousel-item>

      <!-- <el-carousel-item data-tauri-drag-region>
        <div id="cpu-chart" data-tauri-drag-region></div>
      </el-carousel-item> -->

      <!-- 
      <el-carousel-item data-tauri-drag-region>
        <div id="memory-chart" data-tauri-drag-region></div>
      </el-carousel-item> -->
      <!-- 
      <el-carousel-item data-tauri-drag-region>
        <div id="swap-chart" data-tauri-drag-region></div>
      </el-carousel-item> -->
    </el-carousel>


  </div>
</template>

<style scoped>
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: transparent;
}

#custom-container {
  background-color: rgba(255, 255, 255, 0);
  justify-content: center;
  align-items: center;
  text-align: center;
}

.el-carousel__item .item {
  color: #4d4d4d;
  opacity: 0.75;
  line-height: auto;
  margin: 0;
  text-align: center;
}

.ball01 {
  width: 200px;
  height: 200px;
  background-color: transparent;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;

  .chart-box1 {
    width: 160px;
    height: 160px;

    :deep(canvas) {
      border-radius: 50%;
    }
  }

  #cpu-chart {
    width: 200px;
    height: 200px;
  }

  #memory-chart {
    width: 200px;
    height: 200px;
  }

  #swap-chart {
    width: 200px;
    height: 200px;
  }
}
</style>
